﻿using Abp.Domain.Repositories;
using Quartz;
using SportsPlatform.Application.Repository.CompetitionProjectRepository;
using SportsPlatform.Application.Repository.RegistrationInfoRepository;
using SportsPlatform.Global;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Redis;
using SportsPlatform.Repository.CompetitionRepository;
using SportsPlatform.Repository.CoreEntity;
using SportsPlatform.SqlExecuter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.Application.QuartzJobs
{
    /// <summary>
    /// 定时更新赛事状态作业
    /// </summary>
    [DisallowConcurrentExecution]
    public class UpdateCompetitionStateJob : IJob
    {
        /// <summary>
        /// 赛事仓储
        /// </summary>
        private readonly ICompetitionRepository _competitionRepository;
        /// <summary>
        /// Redis仓储实例
        /// </summary>
        private readonly IRedisRepository _redisRepository;
        /// <summary>
        /// 报名信息仓储
        /// </summary>
        private readonly IRegistrationInfoRepository _registrationInfoRepository;
        /// <summary>
        /// 赛事项目仓储
        /// </summary>
        private readonly ICompetitionProjectRepository _competitionProjectRepository;

        private readonly ISqlExecuterRepository _sqlExecuterRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        public UpdateCompetitionStateJob()
        {
            _competitionRepository = new CompetitionRepository();
            _redisRepository = new RedisRepository();
            _sqlExecuterRepository = new SqlExecuterRepository();
            _competitionProjectRepository = new CompetitionProjectRepository();
            _registrationInfoRepository = new RegistrationInfoRepository();
        }

        /// <summary>
        /// 定时更新赛事状态作业执行
        /// </summary>
        /// <param name="context">作业执行对象</param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            int totalCount = 0;

            #region 查询赛事
            var sqlKey = "sqls:sql:query_T_B_Competition";
            var strSQL = UldAdminGlobalContext.Configuration.GetSection(sqlKey).Value;

            var res = await this._competitionRepository.SqlQueryAsync(new QueryCondition(), totalCount, strSQL);
            #endregion

            #region 查询赛事项目
            var strPorjectKey = "sqls:sql:query_T_B_CompetitionProject";
            var strProjectSQL = UldAdminGlobalContext.Configuration.GetSection(strPorjectKey).Value;

            var projects = await this._competitionProjectRepository.SqlQueryAsync(new QueryCondition(), totalCount, strProjectSQL);
            #endregion

            #region 查询报名信息
            //var sqlRegistrKey = "sqls:sql:query_T_B_RegistrationInfo";
            //var strRegistrSQL = UldAdminGlobalContext.Configuration.GetSection(sqlRegistrKey).Value;

            //var registrationInfos = await this._registrationInfoRepository.SqlQueryAsync(new QueryCondition(), totalCount, strRegistrSQL);
            #endregion

            var state = 0;
            DateTime date = DateTime.Now;

            #region 更新赛事状态
            if (res.Count > 0)
            {
                res.ForEach(r =>
                {
                    // 赛事状态（0：关闭；1：待发布；2：报名未开始；3：正在报名；4：报名结束待比赛；5：正在比赛；6：比赛结束）
                    var whereProjects = projects.Where(p => p.CompetitionId == r.Id).ToList();
                    if (whereProjects.Count == 0)
                    {
                        UldLoggerContext.Info("赛事名称：" + r.Name + "赛事项目条数为" + whereProjects.Count);
                        return;
                    }
                    if (r.SignUpBeginTime <= date && r.SingUpEndTime >= date && r.State != 3)
                    {
                        state = 3;
                        var sql = "UPDATE T_B_Competition SET State='" + state + "'where Id='" + r.Id + "'";
                        _sqlExecuterRepository.Execute(sql, null);
                    }
                    else if (r.SingUpEndTime < date && date < r.MatchBeginTime && r.State != 4)
                    {
                        state = 4;

                        var sql = "UPDATE T_B_Competition SET State='" + state + "'where Id='" + r.Id + "'";

                        _sqlExecuterRepository.Execute(sql, null);
                    }
                    else if (r.MatchBeginTime <= date && r.MatchEndTime >= date && r.State != 5)
                    {
                        state = 5;

                        var sql = "UPDATE T_B_Competition SET State='" + state + "'where Id='" + r.Id + "'";

                        _sqlExecuterRepository.Execute(sql, null);
                    }
                    else if (r.MatchEndTime < date && r.State != 6)
                    {
                        state = 6;

                        var sql = "UPDATE T_B_Competition SET State='" + state + "'where Id='" + r.Id + "'";

                        _sqlExecuterRepository.Execute(sql, null);
                    }
                });
            }
            else
            {
                UldLoggerContext.Warn("暂时没有赛事更新");
            }
            #endregion

            #region 更新赛事项目状态 
            //更新之前查询在次查询赛事信息，赛事会更新状态，保证实时性
            res = await this._competitionRepository.SqlQueryAsync(new QueryCondition(), totalCount, strSQL);

            //状态（0：关闭；1：待报名；2：正在报名；3：待分组；4：待签到；5：正在比赛；6：比赛结束）
            projects.ForEach(p =>
            {
                //比赛开始时间
                var gameBeginDate = Convert.ToDateTime(p.GameBeginTime);
                //比赛结束时间
                var gameEndDate = Convert.ToDateTime(p.GameEndTime);
                var cmp = res.FirstOrDefault(r => r.Id == p.CompetitionId);
                if (cmp != null)
                {
                    if (cmp.State == 3 && date < gameBeginDate && p.State < 2)
                    {
                        state = 2;
                        var sql = "UPDATE T_B_CompetitionProject SET State='" + state + "'where Id='" + p.Id + "'";
                        _sqlExecuterRepository.Execute(sql, null);
                    }
                    else if (cmp.State == 4 && p.State < 3)
                    {
                        state = 3;
                        var sql = "UPDATE T_B_CompetitionProject SET State='" + state + "'where Id='" + p.Id + "'";
                        _sqlExecuterRepository.Execute(sql, null);
                    }
                    else if (date > cmp.MatchBeginTime && date < gameBeginDate && p.State < 4)
                    {
                        state = 4;
                        var sql = "UPDATE T_B_CompetitionProject SET State='" + state + "'where Id='" + p.Id + "'";
                        _sqlExecuterRepository.Execute(sql, null);
                    }
                }
                if (date > gameBeginDate && date < gameEndDate && p.State < 5)
                {
                    state = 5;
                    var sql = "UPDATE T_B_CompetitionProject SET State='" + state + "'where Id='" + p.Id + "'";
                    _sqlExecuterRepository.Execute(sql, null);
                }
            });

            #endregion
        }
    }
}
